<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <link rel="stylesheet" href="./css/bootstrap.min.css" />
  <style>
    .form-select {
      width: 103px;
      display: inline-block;
    }

    .col-form-label {
      text-align: right;
    }

    .figure-img {
      width: 100px;
      height: 100px;
    }

    #upload {
      display: none;
    }

    .figure-caption {
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="container">
    <h1 class="p-5">个人设置</h1>
    <form class="col-6">
      <div class="row mb-3">
        <label class="col-form-label col-3">用户名：</label>
        <div class="col-7">
          <input id="username" disabled class="form-control col-9" type="text" />
        </div>
      </div>
      <div class="row mb-3">
        <label class="col-form-label col-3">籍贯：</label>
        <div class="col-9">
          <select class="form-select col-4" name="province">
            <option value="">--省--</option>
          </select>
          <select class="form-select col-4" name="city">
            <option value="">--市--</option>
          </select>
          <select class="form-select col-4" name="county">
            <option value="">--县--</option>
          </select>
        </div>
      </div>
      <div class="row mb-3">
        <label class="col-form-label col-3">头像：</label>
        <div class="col-9">
          <figure class="figure">
            <input type="file" id="upload" />
            <img src="./imgs/default.jpg" class="figure-img img-fluid rounded" alt="..." />
            <figcaption class="figure-caption">修改头像</figcaption>
          </figure>
        </div>
      </div>
      <div class="row mb-3">
        <label class="col-3"></label>
        <div class="col-9">
          <button class="btn btn-primary">保存</button>
        </div>
      </div>
    </form>
  </div>

  <script src="./lib/bootstrap.min.js"></script>
  <script src="./lib/axios.js"></script>
  <script src="./lib/form-value.js"></script>
  <script src="./lib/request.js"></script>

  <script>
    // axios({
    //   method: 'GET',
    //   url: '/user/info',
    //   // headers: {
    //   //   Authorization: localStorage.getItem('mytoken')
    //   // }
    // }).then(({ data: res }) => {
    //   console.log(res);
    // })

    // 到达首页，获取用户的信息
    ; (async function () {
      const { data: res } = await axios.get('/user/info')
      document.querySelector('#username').value = res.data.username;
      // console.log(res);

      // 判断是否有头像，进入的时候显示
      if (res.data.avatar) {
        document.querySelector('img').src = res.data.avatar
      }

      // 判断是否有省市县
      if ( res.data.county) {
        // 获取市县
        let p1 = axios.get('/api/city', { params: { pname: res.data.province } });
        let p2 = axios.get('/api/county', { params: { pname: res.data.province, cname: res.data.city } });

        const [{ data: res1 }, { data: res2 }] = await Promise.all([p1, p2]);
        let arr1 = [`<option value="">--市--</option>`];
        let arr2 = [`<option value="">--县--</option>`];
        res1.forEach(item => arr1.push(`<option value="${item}">${item}</option>`));
        res2.forEach(item => arr2.push(`<option value="${item}">${item}</option>`));
        city.innerHTML = arr1.join('');
        county.innerHTML = arr2.join('');
        // console.log(qqq);
        province.value = res.data.province;
        city.value = res.data.city;
        county.value = res.data.county;
      }
    })();

    // 

    let province = document.querySelector('[name = province]');
    let city = document.querySelector('[name=city]');
    let county = document.querySelector('[name=county]');
    //打开页面获取省份
    ; (async function () {
      const { data: res } = await axios.get('/api/province');
      let arr = [`<option value="">--省--</option>`];
      res.forEach(item => arr.push(`<option value="${item}">${item}</option>`));
      province.innerHTML = arr.join('')
    })();

    // 当改变省的时候，获取市
    province.addEventListener('change', async function () {
      county.innerHTML = `<option value="">--县--</option>`
      if (this.value === '') {
        return city.innerHTML = `<option value="">--市--</option>`
      }

      const { data: res } = await axios.get('/api/city', { params: { pname: this.value } });
      let arr = [`<option value="">--市--</option>`];
      res.forEach(item => arr.push(`<option value="${item}">${item}</option>`));
      city.innerHTML = arr.join('')
    })

    // 当给边市的时候，县也改变
    city.addEventListener('change', async function () {
      if (this.value === '') {
        return city.innerHTML = `<option value="">--县--</option>`
      }

      const { data: res } = await axios.get('/api/county', { params: { pname: province.value, cname: city.value } });
      let arr = [`<option value="">--县--</option>`];
      res.forEach(item => arr.push(`<option value="${item}">${item}</option>`));
      county.innerHTML = arr.join('')
    })

    //点击保存，获取用户选择的省市县。提交给接口
    document.querySelector('button').addEventListener('click', async function (e) {
      e.preventDefault();

      // 用val插件获取值
      let data = val(document.querySelector('form'));
      // 提交
      const { data: res } = await axios.post('/user/info', data);
      // 提示信息
      if (res.status === 0) {
        alert(res.message)
      }
    })

    // 头像上传
    document.querySelector('figcaption').addEventListener('click', function () {
      document.querySelector('#upload').click()
    })
    document.querySelector('#upload').addEventListener('change', async function () {
      // console.dir(this);
      if (this.files.length > 0) {
        let fileObj = this.files[0];
        let fd = new FormData();
        fd.append('avatar', fileObj);
        const { data: res } = await axios.post('/user/avatar', fd);
        if (res.status === 0) {
          document.querySelector('img').src = res.data;
          alert(res.message)
        }
      }
    })
  </script>
</body>

</html>